package com.itheima.register.web;

import com.itheima.register.pojo.User;
import com.itheima.register.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //首先解决中文乱码的问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //将浏览器注册页面发送给服务器的请求数据封装到map集合中
        Map<String, String[]> map = request.getParameterMap();
        //创建user对象
        User user = new User();

        //将数据封装到user对象中
        try {
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //通过业务类对象调用方法,注册用户
        int result = new UserService().registerUser(user);
        //判断结果
        if (result == 1) {
            //说明注册成功,跳转到登录页面
            response.getWriter().println("恭喜您注册成功,欢迎来到德莱联盟!");
            response.setHeader("refresh","2;url=http://localhost:8080/login.html");
            //response.sendRedirect("/login.html");
        } else if (result == 3) {//当结果为3时
            PrintWriter pw = response.getWriter();
            pw.print("<script>");
            pw.print("alert('用户名密码不能为空!请重新输入!');");
            pw.print("location.href='http://localhost:8080/register.html';");
            pw.print("</script>");
        }else if (result == 2) {
            PrintWriter pw = response.getWriter();
            pw.print("<script>");
            pw.print("alert('用户已被注册！请重新操作');");
            pw.print("location.href='http://localhost:8080/register.html';");
            pw.print("</script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
